package com.zxy.allSearcher.datasource;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zxy.allSearcher.common.ErrorCode;
import com.zxy.allSearcher.exception.BusinessException;
import com.zxy.allSearcher.model.entity.Picture;
import com.zxy.allSearcher.model.enums.SearchTypeEnum;
import com.zxy.allSearcher.model.vo.PostVO;
import com.zxy.allSearcher.model.vo.SearchVO;
import com.zxy.allSearcher.model.vo.UserVO;
import com.zxy.allSearcher.utils.PageUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 注册器模式（类似单例模式）
 * 据鱼皮透露，spring底层bean的创建也使用了注册器，通过map来存储
 * 思考：静态是否更加方便
 */
@Component
public class DataSourceRegistry {
    Map<String, DataSource> typeDataSourceMap;
    @Resource
    private PictureDataSource pictureDataSource;
    @Resource
    private UserDataSource userDataSource;
    @Resource
    private PostDataSource postDataSource;

    // 感觉设置为静态提升效率，鱼皮的单例模式可能更好
    // 等成员属性注入后执行，否则map一开始初始化时，获取不到注入的bean；
    @PostConstruct
    public void doInit() {
        typeDataSourceMap = new HashMap<String, DataSource>() {{
            put(SearchTypeEnum.POST.getValue(), postDataSource);
            put(SearchTypeEnum.USER.getValue(), userDataSource);
            put(SearchTypeEnum.PICTURE.getValue(), pictureDataSource);
        }};
    }
    /**
     * 根据类型获取数据源
     * */
    public DataSource getDataSourceByType(String type) {
        if (typeDataSourceMap == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"数据类型不合法");
        }
        return typeDataSourceMap.get(type);
    }
}
